package com;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

public class SendAttachmentMailServlet extends HttpServlet {

	private static final long serialVersionUID = -1408700020471642036L;
	private ServletContext sc;
	private String savePath;
	private Map<String, String> parameters = new HashMap<String, String>();

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		File file = this.doAttachment(request);

		MultiPartEmail email = new MultiPartEmail();
		email.setCharset("UTF-8");
		email.setHostName("smtp.126.com");
		email.setAuthentication("blackbeetle", "zzq123***");

		try {
			email.addTo(parameters.get("to"));
			email.setFrom(parameters.get("from"));
			email.setSubject(parameters.get("subject"));
			email.setMsg(parameters.get("content"));
			if (file != null) {
				EmailAttachment attachment = new EmailAttachment();
				attachment.setPath(file.getPath());
				attachment.setDisposition(EmailAttachment.ATTACHMENT);
				attachment.setName(file.getName());
				email.attach(attachment);
			}
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功！");
		} catch (EmailException e) {
			e.printStackTrace();
			request.setAttribute("sendmail.message", "邮件发送不成功！");
		}

		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);

	}

	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (item.isFormField()) {
					parameters.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						File tempFile = new File(item.getName());
						file = new File(sc.getRealPath("/") + savePath,
								tempFile.getName());
						item.write(file);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("upload.message", "上传文件不成功！");
		}
		return file;
	}

	public void init(ServletConfig config) {
		savePath = config.getInitParameter("savePath");
		sc = config.getServletContext();
	}

}
